package org.xin.security.config.authentication;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;
import org.xin.common.result.ResultCode;
import org.xin.common.util.XinUtil;
import org.xin.security.pojo.bo.SecurityUser;
import org.xin.security.service.impl.UserDetailsServiceImpl;

/**
 * @author ：xin
 * @date ：Created in 2021/10/3
 * @desc <p>  </p>
 * @modified By：$
 * @version: $
 */
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsServiceImpl userDetailsService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        // 获取前端表单中输入后返回的用户名、密码
        String username = (String) authentication.getPrincipal();
        String password = (String) authentication.getCredentials();
        if (XinUtil.hasNull(username, password)) {
            throw new BadCredentialsException("用户名或密码不能为空!");
        }
        SecurityUser securityUser = (SecurityUser) userDetailsService.loadUserByUsername(username);

        boolean isValid = XinUtil.Md5(password.trim(), securityUser.getUser().getSalt()).equalsIgnoreCase(securityUser.getPassword());

//        boolean isValid = SecurityUtil.encryptPassword(password.trim() + userInfo.getUser().getSalt()).equalsIgnoreCase(userInfo.getUser().getPassword());
        // 验证密码
        if (!isValid) {
            throw new BadCredentialsException(ResultCode.USER_UNAUTHORIZED.getDesc());
        }
        return new UsernamePasswordAuthenticationToken(securityUser, null);
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
